package com.code.util;

import java.util.Iterator;

public class StrUtil {
	// public static final String EMPTY = "";
	// public static final int INDEX_NOT_FOUND = -1;
	// private static final int PAD_LIMIT = 8192;
	// private static final String[] PADDING = new String[65535];
	//
	// static {
	// PADDING[32] =
	// "                                                                ";
	// }
	//
	public static boolean isEmpty(String str) {
		return (str == null) || (str.length() == 0);
	}

	public static boolean equals(String str1, String str2) {
		return str1 == null ? str2 == null : str1.equals(str2);
	}

	public static int indexOfAny(String str, String searchChars) {
		if ((isEmpty(str)) || (isEmpty(searchChars))) {
			return -1;
		}
		return indexOfAny(str, searchChars.toCharArray());
	}

	public static int indexOfAny(String str, char[] searchChars) {
		if ((isEmpty(str)) || searchChars == null || searchChars.length == 0) {
			return -1;
		}
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			for (int j = 0; j < searchChars.length; j++) {
				if (searchChars[j] == ch) {
					return i;
				}
			}
		}
		return -1;
	}

	public static String join(Iterator<?> iterator, String separator) {
		if (iterator == null) {
			return null;
		}
		StringBuffer buf = new StringBuffer(256);
		while (iterator.hasNext()) {
			Object obj = iterator.next();
			if (obj != null) {
				buf.append(obj);
			}
			if ((separator != null) && (iterator.hasNext())) {
				buf.append(separator);
			}
		}
		return buf.toString();
	}

	public static String replace(String text, String repl, String with) {
		return replace(text, repl, with, -1);
	}

	public static String replace(String text, String repl, String with, int max) {
		if ((text == null) || (isEmpty(repl)) || (with == null) || (max == 0)) {
			return text;
		}
		StringBuffer buf = new StringBuffer(text.length());
		int start = 0;
		int end = 0;
		for (; (end = text.indexOf(repl, start)) != -1 && max != 0;) {
			buf.append(text.substring(start, end)).append(with);
			start = end + repl.length();
			max--;
		}
		buf.append(text.substring(start));
		return buf.toString();
	}
}